#include "measuretime.h"

#include <qdebug.h>
//#include <QCoreApplication>
//#include <iostream>
//#include <sched.h>
//#include<stdio.h>
//#include <sys/mman.h>
//#include <native/task.h>
//#include <native/timer.h>
#include <sys/time.h>
#include <time.h>
//#include <rtdk.h>

using namespace std;

MeasureTime::MeasureTime(QString measureComment, int isPrint,  int printInterval, int measureCount)
{
    this->measureComment=measureComment;
    this->isPrint=isPrint;
    this->printInterval=printInterval;
    this->measureCount=measureCount;
    callCount=0;
    minTime=1000000000;
    maxTime=0;
    printCount=0;
    isPeriodTimeInitialed=0;
    addTime = 0.0;

    qDebug()<<measureComment<<"isPrint="<<isPrint<<"printInverval="<<printInterval<<"measureCount"<<measureCount;


}
void MeasureTime::reset()
{
    callCount=0;
    minTime=1000000000;
   // maxTime=0;
    addTime=0.0;
}

void MeasureTime:: recordInTime()
{
     clock_gettime(CLOCK_REALTIME, &inTime);
}

int MeasureTime:: recordOutTime()
{
      callCount++;
     clock_gettime(CLOCK_REALTIME, &outTime);
     int time;
      time=outTime.tv_nsec+1000000000*outTime.tv_sec-inTime.tv_nsec-1000000000*inTime.tv_sec;
    maxTime=max(maxTime,time);
    //minTime=time;
    minTime = min(minTime,time);
    addTime+=time;
    averageTime=addTime/callCount;

    if(callCount>=measureCount)
    {
        printCount++;
        if(1==isPrint && printCount==printInterval )
        {
             printCount=0;
             qDebug()<<measureComment<<"units is us|"<<"minTime = "<<minTime/1000<<"; maxTime = "<<maxTime/1000<<
                       "; averageTime = "<<averageTime/1000 << "allTime = " << addTime/1000;
        }
        //reset();
        callCount = 0;
    }

    return time;
}

void MeasureTime::recordPeirodTime()
{
    if(isPeriodTimeInitialed==0)
    {
        isPeriodTimeInitialed=1;
        recordInTime();
    }
    else
    {
        recordOutTime();
       // inTime.tv_nsec=outTime.tv_nsec;
       // inTime.tv_sec=outTime.tv_sec;
        inTime=outTime;

    }
}

